import { AxiosProgressEvent } from 'axios';
import { defineStore } from 'pinia';
import { ref } from 'vue';

import {
  deleteLogo as deleteLogoApi,
  getLogoBase64String as getLogoBase64StringApi,
  uploadLogo as uploadLogoApi,
} from '@/api/file';
import {
  setAppDescription as setAppDescriptionApi,
  setAppTitle as setAppTitleApi,
} from '@/api/sys/admin/settings';
import { ExchangeQuotationEnum } from '@/enums/exchangeQuotationEnum';
import { useI18n } from '@/locale';
import logoImg from '@/static/images/logos/logo.png';
import { UploadFileParams } from '#/request';

/** 网站/应用名称 */
const APP_TITLE = import.meta.env.VITE_APP_TITLE;
/** 网站/应用描述 */
const APP_DESC = import.meta.env.VITE_APP_DESC;

/** 系统偏好设置状态 */
interface PreferenceState {
  /**  编号 */
  Id?: string | bigint | null;

  /**  组织机构编号 */
  OrganizationId?: string | bigint | null;

  /**  已初始化 */
  Initialized?: boolean | null;
  /**  负责人 */
  CEO?: string | null;
  /**  财务主管 */
  CFO?: string | null;
  /**  本位币 */
  MainCurrencyId?: string | null;
  /**  系统货币 */
  SysCurrencyId?: string | null;
  /**  汇率标价方法 */
  ExchangeQuotation?: ExchangeQuotationEnum | null;

  /**  数量小数位数 */
  QuantityAccuracy?: number | null;
  /**  单价小数位数 */
  PriceAccuracy?: number | null;
  /**  金额小数位数 */
  AmountAccuracy?: number | null;
  /**  费率小数位数 */
  RateAccuracy?: number | null;
  /**  百分比小数位数 */
  PercentageAccuracy?: number | null;
  /**  度量小数位数 */
  MeasureAccuracy?: number | null;

  /**  公司名称 */
  CompanyName?: string | null;
  /**  纳税人识别号(统一社会信用代码) */
  TaxpayerNumber?: string | null;
  /**  公司地址 */
  CompanyAddr?: string | null;
  /**  公司电话 */
  CompanyTel?: string | null;
  /**  公司开户银行 */
  CompanyBank?: string | null;
  /**  公司开户行账号 */
  CompBakAccount?: string | null;

  /** 网站/应用LOGO */
  logoSrc?: string | null;
  /** 网站/应用标题 */
  appTitle?: string | null;
  /** 网站/应用描述 */
  appDescription?: string | null;
  /** 网站/应用子描述 */
  appSubdescription?: string | null;
}

/** 初始状态 */
const initState: PreferenceState = {
  Id: undefined,
  OrganizationId: undefined,
  Initialized: undefined,
  CEO: undefined,
  CFO: undefined,
  MainCurrencyId: undefined,
  SysCurrencyId: undefined,
  ExchangeQuotation: undefined,
  QuantityAccuracy: undefined,
  PriceAccuracy: undefined,
  AmountAccuracy: undefined,
  RateAccuracy: undefined,
  PercentageAccuracy: undefined,
  MeasureAccuracy: undefined,
  CompanyName: undefined,
  TaxpayerNumber: undefined,
  CompanyAddr: undefined,
  CompanyTel: undefined,
  CompanyBank: undefined,
  CompBakAccount: undefined,

  logoSrc: undefined,
  appTitle: undefined,
  appDescription: undefined,
  appSubdescription: undefined,
};

/** 系统偏好设置存储 */
export const usePreferenceStore = defineStore(
  'app-preference',
  () => {
    /** 系统偏好设置信息 */
    const state = ref<PreferenceState>({ ...initState });

    const { t } = useI18n();

    /** 获取系统偏好 */
    const get = () => {
      return state.value;
    };
    /** 设置系统偏好 */
    const set = (val: PreferenceState) => {
      state.value = { ...state.value, ...val };
    };
    /** 重置系统偏好 */
    const reset = () => {
      state.value = { ...initState };
    };

    /** 获取LOGO */
    const getLogo = computed(() => unref(state).logoSrc || logoImg);
    /** 获取应用标题 */
    const getAppTitle = computed(() => unref(state).appTitle || APP_TITLE);
    /** 获取应用描述 */
    const getAppDescription = computed(
      () => unref(state).appDescription || APP_DESC || t('sys.login.signInTitle'),
    );
    /** 获取应用子描述 */
    const getAppSubdescription = computed(
      () => unref(state).appSubdescription || t('sys.login.signInDesc'),
    );

    /** 重置LOGO */
    const resetLogo = async () => {
      const result = await deleteLogoApi();
      if (result.Type === 200) {
        setLogo(undefined);
      }
      return result;
    };

    /** 上传LOGO */
    const uploadLogo = async (
      params: UploadFileParams,
      onUploadProgress: (progressEvent: AxiosProgressEvent) => void,
    ) => {
      const result = await uploadLogoApi(params, onUploadProgress);
      const logo = await getLogoBase64StringApi();
      if (logo) {
        setLogo(logo);
      }
      return result;
    };

    /** 设置LOGO */
    const setLogo = (logo?: string | null) => {
      const logoSrc = logo;
      state.value = { ...state.value, logoSrc };
      // #region 系统网站图标处理
      // #ifdef H5
      let $favicon = document.querySelector('link[rel="icon"]') as HTMLLinkElement;
      if ($favicon !== null) {
        $favicon.href = unref(getLogo);
      } else {
        $favicon = document.createElement('link');
        $favicon.rel = 'icon';
        $favicon.href = unref(getLogo);
        document.head.appendChild($favicon);
      }
      // #endif
      // #endregion
    };

    /** 设置应用标题 */
    const setAppTitle = async (title?: string | null, sendRequest = true) => {
      if (sendRequest) {
        const result = await setAppTitleApi(title);
        if (result.Type === 200) {
          state.value = { ...state.value, appTitle: title };
        }
        return result.Type === 200;
      } else {
        state.value = { ...state.value, appTitle: title };
        return true;
      }
    };

    /** 设置应用描述 */
    const setAppDescription = async (description?: string | null, sendRequest = true) => {
      const { appSubdescription } = unref(state);
      if (sendRequest) {
        const result = await setAppDescriptionApi({
          Description: description,
          Subdescription: appSubdescription,
        });
        if (result.Type === 200) {
          state.value = { ...state.value, appDescription: description };
        }
        return result.Type === 200;
      } else {
        state.value = { ...state.value, appDescription: description };
        return true;
      }
    };

    /** 设置应用子描述 */
    const setAppSubdescription = async (subdescription?: string | null, sendRequest = true) => {
      const { appDescription } = unref(state);
      if (sendRequest) {
        const result = await setAppDescriptionApi({
          Description: appDescription,
          Subdescription: subdescription,
        });
        if (result.Type === 200) {
          state.value = { ...state.value, appSubdescription: subdescription };
        }
        return result.Type === 200;
      } else {
        state.value = { ...state.value, appSubdescription: subdescription };
        return true;
      }
    };

    return {
      /** 系统偏好设置信息 */
      state,
      /** 获取系统偏好 */
      get,
      /** 设置系统偏好 */
      set,
      /** 重置系统偏好 */
      reset,
      /** 获取LOGO */
      getLogo,
      /** 获取应用标题 */
      getAppTitle,
      /** 获取应用描述 */
      getAppDescription,
      /** 获取应用子描述 */
      getAppSubdescription,
      /** 重置LOGO */
      resetLogo,
      /** 上传LOGO */
      uploadLogo,
      /** 设置LOGO */
      setLogo,
      /** 设置应用标题 */
      setAppTitle,
      /** 设置应用描述 */
      setAppDescription,
      /** 设置应用子描述 */
      setAppSubdescription,
    };
  },
  {
    persist: false, // 如果需要持久化就写 true, 不需要持久化就写 false（或者去掉这个配置项）。
  },
);
